package com.bbs.utils;

import net.coobird.thumbnailator.Thumbnails;

import java.io.File;
import java.io.IOException;

/**
 * @author: ZackYoung
 * @time: 2020/11/14
 */
public class PicUtil {

    /**
     * 图片原比列压缩
     * @param imageFile
     * @param desPath
     * @param desFileSize
     * @param accuracy
     * @return
     * @throws IOException
     */
    public static File commpressPicForScaleSize(File imageFile, String desPath, long desFileSize, double accuracy) throws IOException {

        long srcFileSize = imageFile.length();
        System.out.println("源图片：" + imageFile.getName() + "，大小：" + srcFileSize / 1024
                + "kb");

        // 1、先转换成jpg
        Thumbnails.of(imageFile).scale(1f).asBufferedImage();
        //按照比例进行缩放
        imgScaleSize(desPath, desFileSize, accuracy);

        File desFile = new File(desPath);
        System.out.println("目标图片：" + desPath + "，大小" + desFile.length()
                / 1024 + "kb");
        System.out.println("图片压缩完成！");


        return desFile;
    }

    /**
     * 图片尺寸不变，压缩文件大小
     */
    private static void imgScaleSize(String desPath, long desFileSize,
                                     double accuracy) throws IOException {
        File fileName = new File(desPath);
        long fileNameSize = fileName.length();
        //判断大小，如果小于指定大小，不压缩；如果大于等于指定大小，压缩
        if (fileNameSize <= desFileSize * 1024) {
            return;
        }
        //图片尺寸不变，压缩图片文件大小
        //图片尺寸不变，压缩图片文件大小outputQuality实现,参数1为最高质量
        Thumbnails.of(desPath).scale(1f).outputQuality(accuracy).toFile(desPath);
        System.out.println("图片尺寸不变，压缩文件大小");
        imgScaleSize(desPath, desFileSize, accuracy);
    }

}
